package org.example.custom.mybatis.config;

import org.apache.commons.lang3.StringUtils;
import org.example.custom.mybatis.annotatiton.CustomMapperScan;
import org.example.custom.mybatis.util.ClassScaner;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;
import java.util.Set;


public class MapperBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        //扫描注解
        Map<String, Object> annotationAttributes = importingClassMetadata
                .getAnnotationAttributes(CustomMapperScan.class.getName());
        String[] basePackages = (String[]) annotationAttributes.get("basePackages");

        if(basePackages != null && basePackages.length > 0){
            for (String basePackage : basePackages) {
                Set<Class> classes = ClassScaner.scan(basePackages,null);
                for (Class<?> clz : classes) {
                    this.registry(registry, clz);
                }


            }
        }

    }

    private void registry(BeanDefinitionRegistry registry, Class<?> clz) {
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(MapperFactoryBean.class);
        BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        beanDefinition.getPropertyValues().addPropertyValue("mapperClz",clz);
        registry.registerBeanDefinition(StringUtils.uncapitalize(clz.getSimpleName()),beanDefinition);
    }
}
